/*
 * ========THE SOLMIX PROJECT=====================================
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.gnu.org/licenses/ 
 * or see the FSF site: http://www.fsf.org. 
 */

package org.solmix.web.security.realm;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author Administrator
 * @version $Id$ 2011-7-5
 */

public class CredentialsMatcher extends CodecSupport implements org.apache.shiro.authc.credential.CredentialsMatcher
{

private static final Logger log = LoggerFactory.getLogger(SimpleCredentialsMatcher.class);

/**
 * {@inheritDoc}
 * 
 * @see org.apache.shiro.authc.credential.CredentialsMatcher#doCredentialsMatch(org.apache.shiro.authc.AuthenticationToken,
 *      org.apache.shiro.authc.AuthenticationInfo)
 */
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    Object tokenCredentials = getCredentials(token);
    Object principal = token.getPrincipal();
    String tokenAfterSrypto;
    if (principal instanceof String) {

        Md5Hash md5 = new Md5Hash(tokenCredentials, ((String) principal).toLowerCase());
        tokenAfterSrypto = md5.toHex();
    } else {
        Md5Hash md5 = new Md5Hash(tokenCredentials, principal);
        tokenAfterSrypto = md5.toHex();
    }
    Object accountCredentials = getCredentials(info);
    String cryptodPsd = null;
    if (accountCredentials instanceof char[])
        cryptodPsd = new String((char[]) accountCredentials);
    else
        cryptodPsd = (String) accountCredentials;
    if (cryptodPsd == null)
        return false;
    return cryptodPsd.equals(tokenAfterSrypto);
}

protected Object getCredentials(AuthenticationToken token) {
    return token.getCredentials();
}

protected Object getCredentials(AuthenticationInfo info) {
    return info.getCredentials();
}
}
